package com.main.common.filters;

import com.main.common.base.resp.RespBody;
import com.main.common.base.resp.RespCode;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
public class GatewayPermissionFilter implements Filter{

    /**
     * 可以初始化Filter配置的初始化参数 filter对象只会创建一次，init方法也只会执行一次。
     *
     * @param filterConfig 配置
     * @throws ServletException 在Servlet的生命周期中发生的任何通用错误
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println(filterConfig);
        System.out.println(filterConfig.getFilterName());
        System.out.println("网关过滤器的初始化方法！" + "，开始访问......");
    }

    /**
     * 过滤器的工作主体
     *
     * @param servletRequest 请求
     * @param servletResponse 响应
     * @param filterChain filterChain
     * @throws IOException 输入/输出操作过程中可能发生的异常情况
     * @throws ServletException 在Servlet的生命周期中发生的任何通用错误
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println(LocalDateTime.now());
        System.out.println("经过过滤器GatewayPermissionFilter");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        String url = String.valueOf(req.getRequestURL());
//        if (url.contains("/websocket/")) {
//            filterChain.doFilter(servletRequest, servletResponse);
//            return;
//        }
        if(req.getHeader("X-Gateway-Token")==null){
            servletResponse.setContentType("application/json; charset=UTF-8");
            RespBody<String> respBody = RespBody.fail(RespCode.BAD_GATEWAY,"请通过网关请求资源","");
            rep.setStatus(respBody.getCode());
            servletResponse.getWriter().write(respBody.toJson());
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("过滤器的执行方法，Servlet向客户端发送的响应被我拦截到了");
    }

    /**
     * 在销毁Filter时自动调用。
     */
    @Override
    public void destroy() {
        System.out.println("网关过滤器的被销毁时调用的方法！开始注销......");
    }
}
